package cn.chendd.utils;

import java.awt.Component;
import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.filechooser.FileSystemView;

public class CommonUtils {

	/**
	 * 打开文件选择对话框，从桌面开始选择文件
	 * @param title 窗口标题
	 * @param suffix 过滤后缀名
	 * @param frame jframe对象
	 * @return 选择文件的路径 ? null
	 */
	public static String getFileChooser(Component frame , String title , String ...suffix){
		JFileChooser chooser = new JFileChooser();
		StringBuilder descritionBuilder = new StringBuilder();
		if(suffix != null && suffix.length != 0){
			for (String s : suffix) {
				descritionBuilder.append("*.").append(s).append(" 或 ");
			}
			if(descritionBuilder.length() > 0){
				descritionBuilder.deleteCharAt(descritionBuilder.length() - 2);
			}
			FileNameExtensionFilter filter = new FileNameExtensionFilter(descritionBuilder.toString() , suffix);
			chooser.setFileFilter(filter);
		}
		FileSystemView systemView = FileSystemView.getFileSystemView();
		chooser.setCurrentDirectory(systemView.getHomeDirectory());
		chooser.setAcceptAllFileFilterUsed(false);
		chooser.setDialogTitle(title);
		int returnValue = chooser.showSaveDialog(frame);
		if(returnValue == JFileChooser.CANCEL_OPTION){
			return null;
		}
		File selectFile = chooser.getSelectedFile();
		if(selectFile.exists() && selectFile.isFile()){
			String filePath = selectFile.getPath();
			return filePath;
		}
		return null;
	}
	
}
